<template>
  <div class="container process-param-input">
    <!-- 表格标签切换区域 -->
    <!-- <div class="table-tabs-bar" style="width: 100%">
      <el-tabs v-model="activeTab" class="table-tabs" @tab-click="handleClick">
        <el-tab-pane label="镀锌1870" name="cgl1870"></el-tab-pane>
        <el-tab-pane label="连退1630" name="cal1630"></el-tab-pane>
        <el-tab-pane label="连退2150" name="cal2150"></el-tab-pane>
        <el-tab-pane label="酸轧2280" name="tcm2280"></el-tab-pane>
      </el-tabs>
    </div> -->
    <el-container>
      <el-header style="height: 10vh">
        <div class="header-serch">
          <el-form :inline="true" :model="searchForm" class="header-form search-form">
            <el-form-item>
              <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link">
                  {{ curLine }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="tcm2280">酸轧2280</el-dropdown-item>
                    <el-dropdown-item command="cal1630">连退1630</el-dropdown-item>
                    <el-dropdown-item command="cal2150">连退2150</el-dropdown-item>
                    <el-dropdown-item command="cgl1870">镀锌1870</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-form-item>
            <el-form-item label="开始时间" class="time-period-picker">
              <el-date-picker v-model="searchForm.startTime" type="datetime" placeholder="开始时间" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="结束时间" class="time-period-picker">
              <el-date-picker v-model="searchForm.endTime" type="datetime" placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="primary" @click="handleInsert">添加</el-button>
              <el-button type="primary" @click="handleExport">导出</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main>
        <el-col>
          <el-row>
            <div style="width: 100%" class="common-div-card table">
              <el-table
                :data="tableData"
                border
                :header-cell-style="{
                  background: '#083885',
                  color: '#ddd',
                  textAlign: 'center',
                  border: '1px solid rgba(255,255,255,0.18)',
                  borderBottom: '1px solid rgba(255,255,255,0.28)',
                }"
                :cell-style="{ textAlign: 'center' }"
                v-loading="tableLoading"
                :show-overflow-tooltip="true"
                ref="tableRef"
                element-loading-text="加载中..."
                element-loading-background="transparent"
              >
                <el-table-column type="index" label="序号" width="80" />
                <el-table-column prop="datetime" label="日期" width="180" />
                <el-table-column prop="crew" label="班" />
                <el-table-column prop="team" label="组" />
                <el-table-column prop="processName" label="名称" />
                <el-table-column prop="coildId" label="卷号" />
                <el-table-column prop="processValue" label="值" />
                <el-table-column label="操作" width="160" fixed="right">
                  <template #default="scope">
                    <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-row>
          <el-row>
            <div class="pagination">
              <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
              />
            </div>
          </el-row>
        </el-col>
      </el-main>
    </el-container>
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="handleClose" ref="detailDialogRef" @closed="cancel" class="detailDialog">
    <div>
      <el-form :model="dialogForm" label-width="auto" ref="dialogFormRef" :rules="formRules">
        <el-form-item label="日期" prop="datetime" required>
          <el-date-picker v-model="dialogForm.datetime" type="datetime" placeholder="日期" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="班" prop="crew" required>
          <el-select v-model="dialogForm.crew" placeholder="请选择" clearable>
            <el-option label="白" value="白" />
            <el-option label="夜" value="夜" />
          </el-select>
        </el-form-item>
        <el-form-item label="组" prop="team" required>
          <el-select v-model="dialogForm.team" placeholder="请选择" clearable>
            <el-option label="A" value="A" />
            <el-option label="B" value="B" />
            <el-option label="C" value="C" />
            <el-option label="D" value="D" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="processName" required>
          <el-select v-model="dialogForm.processName" placeholder="请选择" clearable>
            <el-option label="反射率" value="反射率" />
            <el-option label="平整液浓度" value="平整液浓度" v-if="activeTab === 'cal1630' || activeTab === 'cal2150'" />
            <el-option label="乳化液浓度" value="乳化液浓度" v-if="activeTab === 'tcm2280'" />
            <el-option label="光整液浓度" value="光整液浓度" v-if="activeTab === 'cgl1870'" />
          </el-select>
        </el-form-item>
        <!-- remote multiple reserve-keyword remote-show-suffix :remote-method="remoteMethod" @visible-change="focus" :filter-method="filterMethod"-->
        <el-form-item label="卷号" prop="coildId" :required="dialogForm.processName != '反射率'">
          <el-select
            v-model="dialogForm.coildId"
            filterable
            clearable
            placeholder="请输入卷号"
            :loading="coilLoading"
            loading-text="第一次加载稍慢，正努力加载中..."
            :disabled="dialogForm.processName == '反射率'"
            @visible-change="focus"
          >
            <el-option v-for="item in coilOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="值" prop="processValue" required>
          <el-input v-model="dialogForm.processValue" placeholder="值" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="dialogFormSubmit"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, watch, onUnmounted } from 'vue';
  import { processParamApi } from '/@/api/report/index';
  import * as XLSX from 'xlsx';
  import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
  import type { TabsPaneContext } from 'element-plus';
  import { ArrowDown } from '@element-plus/icons-vue';

  // 搜索表单数据
  const searchForm = reactive({
    startTime: '',
    endTime: '',
    coldCoilId: '',
  });

  const tabTextMap: Record<string, string> = {
    tcm2280: '酸轧2280',
    cal1630: '连退1630',
    cal2150: '连退2150',
    cgl1870: '镀锌1870',
  };

  type ActiveTabKey = keyof typeof tabTextMap | string;
  const activeTab = ref<'tcm2280' | 'cal1630' | 'cal2150' | 'cgl1870'>('tcm2280');
  const curLine = computed(() => {
    return tabTextMap[activeTab.value as ActiveTabKey] ?? '酸轧2280';
  });
  const handleCommand = (command: 'tcm2280' | 'cal1630' | 'cal2150' | 'cgl1870') => {
    if (activeTab.value != command) {
      coilOptions.value = [];
      activeTab.value = command;
      fetchData();
    }
  };

  // const handleClick = (tab: TabsPaneContext, event: Event) => {
  //   const name = String(tab.paneName ?? '');
  //   if (activeTab.value != name) {
  //     coilOptions.value = [];
  //     activeTab.value = name;
  //   }
  // };

  // const activeTab = ref('cgl1870');
  const tableLoading = ref(false);
  const tableRef = ref<any>();
  const dialogVisible = ref(false);
  const dialogTitle = ref('新增');
  const dialogFormRef = ref();
  interface DialogForm {
    indocno: number;
    datetime: string;
    crew: string;
    team: string;
    processName: string;
    processValue: string;
    coildId: number;
  }
  const dialogForm = reactive({
    indocno: 0,
    datetime: '',
    crew: '',
    team: '',
    processName: '',
    processValue: null,
    coildId: '',
  });

  // 定义自定义验证函数
  const validateNumber = (rule: any, value: any, callback: any) => {
    try {
      value = Number(value);
    } catch (e) {
      callback(new Error('值必须是数字'));
    }
    if (value === '' || value === undefined || value === null) {
      callback(new Error('请输入值'));
    } else if (!Number.isFinite(value)) {
      callback(new Error('值必须是数字'));
    } else {
      callback();
    }
  };

  const formRules = {
    datetime: [{ required: true, message: '请选择日期', trigger: 'change' }],
    crew: [{ required: true, message: '请选择班次', trigger: 'change' }],
    team: [{ required: true, message: '请选择组别', trigger: 'change' }],
    processName: [{ required: true, message: '请选择名称', trigger: 'change' }],
    processValue: [
      { required: true, message: '请输入值', trigger: 'blur' },
      { validator: validateNumber, trigger: 'blur' },
    ],
    coildId: [{ required: dialogForm.processName != '反射率', message: '请输入卷号', trigger: 'blur' }],
  };

  // 表格数据
  const tableData = ref([]);

  // 分页大小变化
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    pagination.currentPage = 1; // Reset to first page
    fetchData();
  };

  // 页码变化
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchData();
  };

  // --- Pagination ---
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: tableData.value.length,
  });

  // 监听标签切换（放在 activeTab 定义之后）
  watch(activeTab, (newActiveTab) => {
    console.log('切换到:', newActiveTab);
    pagination.currentPage = 1;
    fetchData();
  });

  // 搜索方法
  const handleSearch = async () => {
    pagination.currentPage = 1;
    fetchData();
  };

  // 重置方法
  const handleReset = async () => {
    searchForm.startTime = '';
    searchForm.endTime = '';
    pagination.currentPage = 1;
    await fetchData();
  };

  // 详情弹窗关闭事件
  const handleClose = (done: () => void) => {
    ElMessageBox.confirm('确定要放弃当前更改吗?')
      .then(() => {
        cancel();
      })
      .catch(() => {
        // catch error
      });
  };

  // 详情弹窗取消事件
  const cancel = () => {
    dialogVisible.value = false;
    dialogForm.datetime = '';
    dialogForm.crew = '';
    dialogForm.team = '';
    dialogForm.processName = '';
    dialogForm.processValue = null;
    dialogForm.coildId = '';
    dialogForm.indocno = 0;
  };

  const fetchData = async () => {
    const param = {
      page: {
        pageIndex: pagination.currentPage,
        pageSize: pagination.pageSize,
      },
      dto: {
        startDate: searchForm.startTime,
        endDate: searchForm.endTime,
        lineCode: activeTab.value,
      },
    };
    try {
      tableLoading.value = true;
      const res = await processParamApi.page(param);
      if (res.data.status != 2000) {
        throw new Error('获取失败');
      }
      tableData.value = res.data.data;
      pagination.total = res.data.count;
      ElMessage.success('获取成功');
    } catch (err: any) {
      console.error('获取失败:' + err.message);
    } finally {
      tableLoading.value = false;
    }
  };

  // 添加方法
  const handleInsert = () => {
    dialogVisible.value = true;
    dialogTitle.value = '新增';
  };

  // 编辑方法
  const handleEdit = (row: any) => {
    dialogVisible.value = true;
    dialogTitle.value = '编辑';
    Object.assign(dialogForm, { ...row });
  };

  // 删除方法
  const handleDelete = async (row: any) => {
    // 添加确认对话框
    ElMessageBox.confirm('确定要删除这条记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res = await processParamApi.delete(row.indocno);
          if (res.data.status != 2000) {
            throw new Error('删除失败');
          }
          ElMessage.success('删除成功');
        } catch (err: any) {
          console.error('删除失败:' + err.message);
          ElMessage.error('删除失败');
        } finally {
          fetchData();
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
  };

  const dialogFormSubmit = async () => {
    dialogFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        // 表单验证通过，提交表单
        const param = {
          indocno: dialogForm.indocno,
          datetime: dialogForm.datetime,
          crew: dialogForm.crew,
          team: dialogForm.team,
          processName: dialogForm.processName,
          processValue: Number(dialogForm.processValue),
          coildId: dialogForm.coildId,
          lineCode: activeTab.value,
        };

        try {
          let res;
          if (dialogTitle.value === '新增') {
            // 新增
            res = await processParamApi.insert(param);
          } else {
            // 编辑
            res = await processParamApi.edit(param);
          }

          if (res.data.status !== 2000) {
            throw new Error(res.data.message || '操作失败');
          }

          ElMessage.success(dialogTitle.value === '新增' ? '新增成功' : '编辑成功');
        } catch (err: any) {
          console.error(err.message);
          ElMessage.error(err.message);
        } finally {
          dialogVisible.value = false;
          fetchData();
        }
      } else {
        // 表单验证失败，提示用户
        ElMessage.error('表单验证失败，请检查输入');
      }
    });
  };

  const handleExport = () => {
    if (!tableData.value.length) {
      ElNotification({
        title: 'Error',
        message: '导出Excel失败: 当前暂无数据',
        type: 'error',
      });
      return;
    }

    try {
      // 动态获取表格列配置
      let columns = tableRef.value?.columns;

      if (!columns || !(Array.isArray(columns) && columns.length)) {
        ElNotification({
          title: 'Error',
          message: '导出Excel失败: 表格列配置错误',
          type: 'error',
        });
        return;
      }

      // 添加新的属性到 headerMap
      const headerMap: Record<string, string> = {
        index: '序号',
      };

      columns = columns.filter((column: any) => {
        return column.property;
      });

      // 构建字段到标签的映射
      columns.forEach((column: any) => {
        if (column.property) {
          headerMap[column.property] = column.label;
        }
      });

      // 构建字段名数组
      const columnProperties = Object.keys(headerMap);

      // 过滤 tableData 中不在 columns 配置中的字段
      const filteredTableData = tableData.value.map((row: any, rowIndex: number) => {
        const filteredRow: any = { index: rowIndex + 1 };
        columnProperties.forEach((property: string) => {
          if (row[property] !== undefined) {
            filteredRow[property] = row[property];
          }
        });
        return filteredRow;
      });

      // 转换数据为 worksheet
      const ws = XLSX.utils.json_to_sheet(filteredTableData, { header: columnProperties });

      // 添加中文表头
      const headerRow = Object.values(headerMap);
      XLSX.utils.sheet_add_aoa(ws, [headerRow], { origin: 'A1' });

      // 创建 workbook 并添加 worksheet
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      // 格式化日期和时间
      const formattedDateTime = new Date()
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        })
        .replace(/\//g, '-')
        .replace(/\s/g, '_')
        .replace(/:/g, '-');

      // 生成 Excel 文件并下载
      XLSX.writeFile(wb, '工艺参数' + formattedDateTime + '.xlsx');
      ElMessage.success('导出成功');
    } catch (error: any) {
      ElMessage.error('导出Excel失败: ' + error.message);
      console.error('导出Excel时出错:', error);
    }
  };

  onMounted(() => {
    fetchData();
  });

  onUnmounted(() => {});

  // --------------------------------------------------------  对话窗卷号筛选相关 --------------------------------
  interface OptionItem {
    value: string;
    label: string;
  }
  const coilOptions = ref<OptionItem[]>([]);
  const coilLoading = ref(false);

  const focus = async (visible: boolean) => {
    try {
      coilLoading.value = true;
      if (visible) {
        if (coilOptions.value.length <= 0) {
          await processParamApi.getCoilList({ lineCode: activeTab.value }).then((res) => {
            // const resCoilList: string[] = res.data.data;
            // coilOptions.value = resCoilList.map((item) => {
            //   return { value: item, label: item };
            // });
            coilOptions.value = res.data.data;
            coilLoading.value = false;
          });
        } else {
          coilLoading.value = false;
        }
      }
      coilLoading.value = false;
    } catch (err: any) {
      coilLoading.value = false;
      console.error('获取卷号列表失败:' + err);
      ElMessage.error('获取卷号列表失败，请重试');
    }
  };
</script>
<style lang="less" scoped>
  @import '/src/views/reportforms/customized/processParameter/deepElement.css';

  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  @box-shadow-hover: 0 8px 32px rgba(0, 0, 0, 0.12);
  @border:1px solid #dcdfe6;

  .container {
    height: 100vh;
    width: 99vw;
    border-radius: @border-radius;
    background: url(/@/assets/images/home/body-bg.jpg) no-repeat;
  }

  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
    font-size: 16px;
  }

  .header-serch {
    display: flex;
    flex: 1;
    justify-content: flex-start;
    align-items: center;
    padding: 20px;
    height: 10vh;
    margin-top: 1vh;
  }

  .header-form {
    display: flex;
    align-items: center;
    gap: 20px;
  }

  .table {
    width: 100%;
    height: 65vh;
    padding: 10px;

    .el-table {
      height: calc(65vh - 20px);
    }
  }
</style>
